var browser = {
  versions: function() {
    console.log(1)
      var u = navigator.userAgent, app = navigator.appVersion;
      return {     //移动终端浏览器版本信息
          trident: u.indexOf('Trident') > -1, //IE内核
          presto: u.indexOf('Presto') > -1, //opera内核
          webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
          gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
          mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
          ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
          android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
          iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
          iPad: u.indexOf('iPad') > -1, //是否iPad
          webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
      };
  } (),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}


// create Agora client
var client = AgoraRTC.createClient({ mode: "live", codec: "vp8" });
var localTracks = {
  videoTrack: null,
  audioTrack: null
};
var remoteUsers = {};
// Agora client options
var options = { 
  appid: null,
  channel: null,
  uid: null,
  token: null,
  role: "audience" // host or audience
};

// the demo can auto join channel with params in url
$(() => {
  var urlParams = new URL(location.href).searchParams;
  options.appid = urlParams.get("appid");
  options.channel = urlParams.get("channel");
  options.token = urlParams.get("token");
  if (options.appid && options.channel) {
    $("#appid").val(options.appid);
    $("#token").val(options.token);
    $("#channel").val(options.channel);
    $("#join-form").submit();
  }
  options.role = "audience"
})
//以host身份加入视频
$("#host-join").click(function (e) {
  options.role = "host"

})

//移除标注
$("#clearMove").click(function (e) {
  console.log('2222')

 

      var _x = $('#circular1').position().left+10;
  　　var _y = $('#circular1').position().top;
      console.log(_x);
      console.log(_y);
  // console.log($("#circular1").position().top());
  // console.log($("#circular1").offset());
  
  // var _x =200;//获得X轴方向移动的值  
  // var _y = 100;//获得Y轴方向移动的值   
  // $("#circularimg").animate({left:_x+"px",top:_y+"px"},10);   
  $("#yuan1").animate({left:_x+"px",top:_y+"px"},10);  
  $("#arrowImg").animate({left:_x + 11+"px",top:_y+"px"},10);   



  $("#squareimg").animate({left:_x+"px",top:_y+"px"},10);   
  console.log("xuiiaisduiasdusdu---------------");
})

// t = setInterval("showAuto()", 5000);
//  function showAuto(){
//   //     var _x = $('#circular1').position().left+10;
//   // 　　var _y = $('#circular1').position().top;
//   //     $("#yuan1").animate({left:_x+"px",top:_y+"px"},10);   
// }


// $("#openShow").click(async function (e) {
//   e.preventDefault();
//   $("#join").attr("disabled", true);
//   try {
//     options.appid = $("#appid").val();
//     options.token = $("#token").val();
//     options.channel = $("#channel").val();
//     await joinshow();
//     if(options.token) {
//       $("#success-alert-with-token").css("display", "block");
//     } else {
//       $("#success-alert a").attr("href", `index.html?appid=${options.appid}&channel=${options.channel}&token=${options.token}`);
//       $("#success-alert").css("display", "block");
//     }
//   } catch (error) {
//     console.error(error);
//   } finally {
//     $("#leave").attr("disabled", false);
//   }
// })

// async function joinshow() {
//   // add event listener to play remote tracks when remote user publishs.
//   client.on("user-published", handleUserPublished);
//   client.on("user-unpublished", handleUserUnpublished);

//   // join a channel and create local tracks, we can use Promise.all to run them concurrently
//   [ options.uid, localTracks.audioTrack, localTracks.videoTrack ] = await Promise.all([
//     // join the channel
//     client.join(options.appid, options.channel, options.token || null),
//     // ** create local tracks, using microphone and screen
//     AgoraRTC.createMicrophoneAudioTrack(),
//     AgoraRTC.createScreenVideoTrack()
//   ]);
 
//   // play local video track
//   localTracks.videoTrack.play("local-player");
//   $("#local-player-name").text(`localVideo(${options.uid})`);

//   // publish local tracks to channel
//   await client.publish(Object.values(localTracks));
//   console.log("publish success");
// }

 




 

//以audience身份进入
$("#audience-join").click(function (e) {
  options.role = "audience"
})

$("#join-form").submit(async function (e) {
  e.preventDefault();
  $("#host-join").attr("disabled", true);
  $("#audience-join").attr("disabled", true);
  try {
    options.appid = $("#appid").val();
    options.token = $("#token").val();
    options.channel = $("#channel").val();
    await join();
    if (options.role === "host") {
      $("#success-alert a").attr("href", `index.html?appid=${options.appid}&channel=${options.channel}&token=${options.token}`);
      if(options.token) {
        $("#success-alert-with-token").css("display", "block");
      } else {
        $("#success-alert a").attr("href", `index.html?appid=${options.appid}&channel=${options.channel}&token=${options.token}`);
        $("#success-alert").css("display", "block");
      }
    }
  } catch (error) {
    console.error(error);
  } finally {
    $("#leave").attr("disabled", false);
  }
})

$("#leave").click(function (e) {
  leave();
})


$("#shareScreen").click(function (e) {
  console.log("--------------------------------------------------3333333333333333333333--");
  $("#local-player").remove();
  $("#local-player-name").remove();
})

async function join() {
  // create Agora client
  client.setClientRole(options.role);

  if (options.role === "audience") {
    // add event listener to play remote tracks when remote user publishs.
    client.on("user-published", handleUserPublished);
    client.on("user-unpublished", handleUserUnpublished);
  }

  // join the channel
  options.uid = await client.join(options.appid, options.channel, options.token || null);

  if (options.role === "host") {
    // create local audio and video tracks
    localTracks.audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
    localTracks.videoTrack = await AgoraRTC.createCameraVideoTrack();
    // play local video track
    localTracks.videoTrack.play("local-player");
    $("#local-player-name").text(`localTrack(${options.uid})`);
    // publish local tracks to channel
    await client.publish(Object.values(localTracks));
    console.log("publish success");
  }else if(options.role === "audience"){
    sleep(3);
    leave();
    $("#leave").attr("disabled", false);
  }
}

async function leave() {
  for (trackName in localTracks) {
    var track = localTracks[trackName];
    if(track) {
      track.stop();
      track.close();
      localTracks[trackName] = undefined;
    }
  }

  // remove remote users and player views
  remoteUsers = {};
  $("#remote-playerlist").html("");

  // leave the channel
  await client.leave();

  $("#local-player-name").text("");
  $("#host-join").attr("disabled", false);
  $("#audience-join").attr("disabled", false);
  $("#leave").attr("disabled", true);
  console.log("client leaves channel success");
}

async function subscribe(user, mediaType) {
  const uid = user.uid;
  // subscribe to a remote user
  await client.subscribe(user, mediaType);
  console.log("subscribe success");
  if (mediaType === 'video') {
    const player = $(`
      <div id="player-wrapper-${uid}">
        <p class="player-name">remoteUser(${uid})</p>
        <div id="player-${uid}" class="player "></div>
      </div>
    `);
    $("#remote-playerlist").append(player);
    user.videoTrack.play(`player-${uid}`);
    if (browser.versions.mobile) {
      console.log('12345')
      //修改视频显示界面的大小
      $('.player').css({
        "height":"480px",
        "width":"320px"
      })
      $("#host-join").click(function (e) {
        options.role = "host"
        // $("#isShowVideo").css('display','block')
        $('.player').css('display','none')
        // var div_Length=$('#remote-playerlist  div').children().length;
        // console.log('1234509000')
        // console.log(div_Length)
       
       

        
      })
      
     var div1 = $('#remote-playerlist').children().not(":last").remove();//删除除了最后一个子节点的所有结点


      

      //如果是手机浏览器就打开浏览器后置摄像头
      // async function join() {
      //   // create Agora client
      //   client.setClientRole(options.role);
      
      //   if (options.role === "audience") {
      //     // add event listener to play remote tracks when remote user publishs.
      //     client.on("user-published", handleUserPublished);
      //     client.on("user-unpublished", handleUserUnpublished);
      //   }
      
        // join the channel
        // options.uid = await client.join(options.appid, options.channel, options.token || null);
      
        // if (options.role === "host") {
        //   // create local audio and video tracks
        //   localTracks.audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        //   localTracks.videoTrack = await AgoraRTC.createCameraVideoTrack();
        //   // play local video track
        //   localTracks.videoTrack.play("local-player");
        //   $("#local-player-name").text(`localTrack(${options.uid})`);
         

        //   // publish local tracks to channel
        //   await client.publish(Object.values(localTracks));
        //   console.log("publish success");
         
        //   //加入房间成功后
        //   // function hasUserMedia() { 
        //   // //check if the browser supports the WebRTC 
        //   //   return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || 
        //   //       navigator.mozGetUserMedia); 
        //   // } 
      
        //   // if (hasUserMedia()) { 
        //   //   navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
        //   //       || navigator.mozGetUserMedia; 
        //   //   //enabling video and audio channels 
        //   //   navigator.getUserMedia(
        //   //   {
        //   //     video: {
        //   //       width:640,
        //   //       height:480,
        //   //       facingMode:"environment"
        //   //     }, 
        //   //     audio: true ,
        //   //   }, function (stream) { 
        //   //       var video = document.querySelector('video'); 
        //   //       //inserting our stream to the video tag     
        //   //       // video.src = window.URL.createObjectURL(stream); //谷歌不支持这样的写法
        //   //     video.srcObject = stream;
        //   //   }, function (err) {}); 
        //   // } else { 
        //   //   alert("WebRTC is not supported"); 
        //   // }


        //     }else if(options.role === "audience"){
        //       sleep(3);
        //       leave();
        //       $("#leave").attr("disabled", false);
        //     }
        //   }
          


      


    }

  }
  if (mediaType === 'audio') {
    user.audioTrack.play();
  }
}

function handleUserPublished(user, mediaType) {
  const id = user.uid;
  remoteUsers[id] = user;
  subscribe(user, mediaType);
}

function handleUserUnpublished(user) {
  const id = user.uid;
  delete remoteUsers[id];
  $(`#player-wrapper-${id}`).remove();
}


function sleep(numberMillis) {
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
      return;
  }
}




    var tagging_div = document.getElementById('tagging');
    var circular_div = document.getElementById('yuan1');
		var square_div = document.getElementById('square');
		var circularimg_div = document.getElementById('circularimg');
		var squareimg_div = document.getElementById('squareimg');
		var tagging_img_div = document.getElementById('tagging_img');
		var arrow_div = document.getElementById('arrowImg');
    var show = document.getElementById('footer');
      // show.style.display = "block" 
		// console.log(show.style.display)
		// 点击显示隐藏标注
    // if(show.style.display == "block"){
    //   $(".container").click (function(){
    //     show.style.display = "none"
    //   //   // alert(11)
    //   })
    // }else{
    
    // }

    // show.onclick=function(e){
    //   show.style.display="none";
    // }

    $('#biaozhu').click(function(){
      $('#tagging_img').css('display','block')
        //白板start
    // room_uuid = 94f95dd0a17811eb8ee9c7e06d87b508
    //这里使用的是nettless文档，所以注册一个nettless账户，从中可以获取sdkToken和aooIdentifier
    var sdkToken = 'NETLESSSDK_YWs9SkV0cUlWSkJFWFU5T0FPdiZub25jZT05NWM4MDU3MC05ZTc4LTExZWItYjBjMy1hMWM0MzMxNTViODkmcm9sZT0wJnNpZz0xYjM2Y2NkZGRkYmExNzViZGM0NzY0MjNmYmU0OWM1NzJjZjJlZGYzY2ExNTU4OGVmNjI3ODc3Zjg5NDBkNGY2';
    var appIdentifier = "dEFYgJuEEeuflpceupk-6Q/N3nXv-CPqMZT9g";
    //'https://cloudcapiv4.herewhite.com/room  这里的地址是别人封装好的
    var url = 'https://cloudcapiv4.herewhite.com/room?token=' + sdkToken;
    var requestInit = {
        method: "POST",
        headers: {
            "content-type": "application/json",
            // "token": sdkToken, // 签发的 SDK Token，需提前准备
        },
      body:JSON.stringify({
        name:'none',
        limit:100,
      })
      
    };
    fetch(url,requestInit).then(function(response){
        return response.json();
    })
    .then(function(json){
      // console.log(json)
      room_uuid.value = json.msg.room.uuid;
      room_token.value = json.msg.roomToken;
      document.getElementById("join_room").disabled = true;
      //注意这里new WhiteWebSdk({appIdentifier: appIdentifier,});要传入一个appIdentifier
      var whiteWebSdk = new WhiteWebSdk({appIdentifier: appIdentifier});
      // console.log(24422145677)
        // console.log(whiteWebSdk)
      whiteWebSdk.joinRoom({
          uuid: room_uuid.value,
          roomToken: room_token.value,
        
        }).then(function(room) {
          console.log("room")
          console.log(room)
          var huitu =  room.bindHtmlElement(document.getElementById('whiteboard'));//将画板显示在网页上
          // console.log(huitu)
          // 把教具切换为「铅笔」
          $('#square').click(function(){
            // console.log('square1')
            room.setMemberState({currentApplianceName: "rectangle"});
          })
          $('#arrowImg').click(function(){
            console.log(room.setMemberState({currentApplianceName: "arrow"}))
            
          })
          $('#clearMove').click(function(){
            // console.log('33333')
            // console.log(whiteWebSdk)
            // console.log(room.setMemberState({currentApplianceName: "eraser"}))
            room.setMemberState({currentApplianceName: "eraser"},function(){});
          })
      });
      console.log("room uuid", json.msg.room.uuid, json.msg.roomToken);
    });
    //白板end





    })
		 //圆
    circular_div.onmousedown=function(ev){
				var ev=ev||event;
				var oLeft=ev.clientX - this.offsetLeft;
				var oTop=ev.clientY - this.offsetTop;
			document.onmousemove=function(ev){
				var ev=ev||event;
				circular_div.style.left=ev.clientX-oLeft+'px';
				circular_div.style.top=ev.clientY-oTop+'px';
			}
			document.onmouseup=function(){
        // for(var i = 0 ;i < 2 ;i++){
          var timer = setInterval(shanshuo,300);
          var timer1 = setInterval(shanshuo1,700);
          function shanshuo(){
            circular_div.style.display = 'block'
          }
          function shanshuo1(){
            circular_div.style.display = 'none'
            var timer2 = setInterval(shanshuo2,300);
            var timer3 = setInterval(shanshuo13,700);
            function shanshuo2(){
              circular_div.style.display = 'block'
            }
            function shanshuo13(){
              circular_div.style.display = 'none'
              var timer4 = setInterval(shanshuo4,300);
              var timer5 = setInterval(shanshuo15,700);
              function shanshuo4(){
                circular_div.style.display = 'block'
              }
              function shanshuo15(){
                circular_div.style.display = 'none'
                clearInterval(timer)
                clearInterval(timer1)
                clearInterval(timer2)
                clearInterval(timer3)
                clearInterval(timer4)
                clearInterval(timer5)
    
              } 
  
            } 
          
          } 
				document.onmousemove=function(){
          document.onmouseup=null;
          //  clearInterval(timer);
        }

        // for(var i = 0;i<4;i++){
        //   if(i==3){
        //     clearInterval(timer);
        //     clearInterval(timer1);

        //   }
        // }
    
			  // }

    }
    }
		// //方
		// squareimg_div.onmousedown=function(ev){
		 
		// 		var ev=ev||event;
		 
		// 		var oLeft=ev.clientX - this.offsetLeft;
		// 		var oTop=ev.clientY - this.offsetTop;
		 
		// 	document.onmousemove=function(ev){
		// 		var ev=ev||event;
		 
		// 		squareimg_div.style.left=ev.clientX-oLeft+'px';
		 
		// 		squareimg_div.style.top=ev.clientY-oTop+'px';
		// 	}
		 
		// 	document.onmouseup=function(){

		// 		document.onmousemove=document.onmouseup=null;
		// 	}
    // }
    // //箭头
    // arrow_div.onmousedown=function(ev){
    //   // console.log(ev)
    //   var ev=ev||event;

    //   var oLeft=ev.clientX - this.offsetLeft;
    //   var oTop=ev.clientY - this.offsetTop;

    // document.onmousemove=function(ev){
    //   // console.log(222)
    //   var ev=ev||event;

    //   arrow_div.style.left=ev.clientX-oLeft+'px';

    //   arrow_div.style.top=ev.clientY-oTop+'px';
    // }

    // document.onmouseup=function(){

    //   document.onmousemove=document.onmouseup=null;
    // }
    // }

    function showdiv(){
      $(".container").click(function(e){
        // console.log(222)
        // console.log(e)
        show.style.display = "block"

      })
    }
    // showdiv()
    // $(".container").click (function(e){
      // console.log(e);
      show.style.display = "none"
      console.log(show.style.display)
      if(show.style.display == "none"){
        // console.log(111)
        showdiv()
        var timershow = setInterval(function(){
          show.style.display = "none"
        },3000)
        $("#footer").mouseover(function(){
          clearInterval(timershow)
        })

       
      }
     
     //判断浏览器是pc端还是手机端start
    // var browser = {
    //   versions: function() {
    //     console.log(1)
    //       var u = navigator.userAgent, app = navigator.appVersion;
    //       return {     //移动终端浏览器版本信息
    //           trident: u.indexOf('Trident') > -1, //IE内核
    //           presto: u.indexOf('Presto') > -1, //opera内核
    //           webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
    //           gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
    //           mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    //           ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    //           android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
    //           iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
    //           iPad: u.indexOf('iPad') > -1, //是否iPad
    //           webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
    //       };
    //   } (),
    //   language: (navigator.browserLanguage || navigator.language).toLowerCase()
    // }
    if (browser.versions.webKit) {
      console.log('12345')
      //修改视频显示界面的大小
      $('.player').css({
        "height":"480px",
        "width":"320px"
      })
      // $("#host-join").click(function (e) {
      //   options.role = "host"
      //   // $("#isShowVideo").css('display','block')
      //   $('.player').css('display','none')
        
      // })
      $('.player').remove()


      

      //如果是手机浏览器就打开浏览器后置摄像头
      // async function join() {
      //   // create Agora client
      //   client.setClientRole(options.role);
      
      //   if (options.role === "audience") {
      //     // add event listener to play remote tracks when remote user publishs.
      //     client.on("user-published", handleUserPublished);
      //     client.on("user-unpublished", handleUserUnpublished);
      //   }
      
        // join the channel
        // options.uid = await client.join(options.appid, options.channel, options.token || null);
      
        // if (options.role === "host") {
        //   // create local audio and video tracks
        //   localTracks.audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        //   localTracks.videoTrack = await AgoraRTC.createCameraVideoTrack();
        //   // play local video track
        //   localTracks.videoTrack.play("local-player");
        //   $("#local-player-name").text(`localTrack(${options.uid})`);
         

        //   // publish local tracks to channel
        //   await client.publish(Object.values(localTracks));
        //   console.log("publish success");
         
        //   //加入房间成功后
        //   // function hasUserMedia() { 
        //   // //check if the browser supports the WebRTC 
        //   //   return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || 
        //   //       navigator.mozGetUserMedia); 
        //   // } 
      
        //   // if (hasUserMedia()) { 
        //   //   navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
        //   //       || navigator.mozGetUserMedia; 
        //   //   //enabling video and audio channels 
        //   //   navigator.getUserMedia(
        //   //   {
        //   //     video: {
        //   //       width:640,
        //   //       height:480,
        //   //       facingMode:"environment"
        //   //     }, 
        //   //     audio: true ,
        //   //   }, function (stream) { 
        //   //       var video = document.querySelector('video'); 
        //   //       //inserting our stream to the video tag     
        //   //       // video.src = window.URL.createObjectURL(stream); //谷歌不支持这样的写法
        //   //     video.srcObject = stream;
        //   //   }, function (err) {}); 
        //   // } else { 
        //   //   alert("WebRTC is not supported"); 
        //   // }


        //     }else if(options.role === "audience"){
        //       sleep(3);
        //       leave();
        //       $("#leave").attr("disabled", false);
        //     }
        //   }
          


      


    }

     //判断浏览器是pc端还是手机端end

      
  
  
